package jupitermouse.site.juc.demo.aqs.reentrantlock;

import java.util.concurrent.locks.*;

/**
 * <p>
 *     ReentrantReadWriteLock 读写锁
 * </p>
 *
 * @author jupiter
 */
public class ReadWriteLockDemo {

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public static void main(String[] args) {
        readWrite();
    }

    static void readWrite(){

        Thread t1 = new Thread(()->{
            read();
        }, "t1");

        Thread t2 = new Thread(()->{
            read();
        }, "t2");

        Thread t3 = new Thread(()->{
            write();
        }, "t3");

        t1.start();
        t2.start();
        t3.start();
    }

    static void read(){
        readLock.lock();
        try {
            System.err.println("当前线程 " + Thread.currentThread().getName() + "进入了读方法");
            Thread.sleep(3000);
            System.err.println("当前线程" + Thread.currentThread().getName() + "退出了读方法");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    static void write(){
        writeLock.lock();
        try {
            System.err.println("当前线程 " + Thread.currentThread().getName() + "进入了写方法");
            Thread.sleep(3000);
            System.err.println("当前线程" + Thread.currentThread().getName() + "退出了写方法");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }
}
